﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.DepartmentUser;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;
using CCWin;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectUsers : CCSkinMain
    {
        private List<UserData> userList = new List<UserData>();
        public UserData SelectedUser { get; private set; }

        public SelectUsers()
        {
            InitializeComponent();
            InitializeForm();
            SetFormIcon();
        }

        private async void InitializeForm()
        {
            this.Text = "选择负责人";
            this.Size = new Size(900, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 加载用户数据
            await LoadUserData();
        }

        /// <summary>
        /// 设置窗体图标
        /// </summary>
        private void SetFormIcon()
        {
            string[] possiblePaths = {
                System.IO.Path.Combine(Application.StartupPath, "..", "..", "Images", "ss.ico")
            };

            string iconPath = possiblePaths.FirstOrDefault(System.IO.File.Exists);
            if (!string.IsNullOrEmpty(iconPath))
            {
                this.Icon = new System.Drawing.Icon(iconPath);
            }
        }

        /// <summary>
        /// 加载用户数据
        /// </summary>
        private async Task LoadUserData()
        {
            try
            {
                Console.WriteLine("=== 开始加载用户部门数据 ===");
                
                Console.WriteLine("正在调用用户部门API...");
                var response = await ApiRequestHelper.GetAsync<ApiUserResponse>("api/Car/GetUserDepartment");
                
                if (response.Success && response.Data?.code == 200 && response.Data.data != null)
                {
                    userList = response.Data.data;
                    Console.WriteLine($"用户部门API调用成功，数据条数: {userList.Count}");
                    LoadUserDataToGrid();
                }
                else
                {
                    var errorMsg = response.Data?.msg ?? response.Message;
                    Console.WriteLine($"用户部门API调用失败: {errorMsg}");
                    ApiRequestHelper.ShowError($"加载用户部门数据失败: {errorMsg}");
                }
                
                Console.WriteLine("=== 用户部门数据加载完成 ===");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载用户部门数据异常: {ex.Message}");
                ApiRequestHelper.ShowError($"加载用户部门数据异常: {ex.Message}");
            }
        }

        /// <summary>
        /// 将用户数据加载到DataGridView
        /// </summary>
        private void LoadUserDataToGrid()
        {
            try
            {
                if (userList == null || userList.Count == 0)
                {
                    ShowAlert("暂无用户部门数据", "提示");
                    return;
                }

                // 绑定数据到DataGridView
                dgvUsers.AutoGenerateColumns = false;
                dgvUsers.DataSource = userList;
                
                // 默认选中第一行
                if (dgvUsers.Rows.Count > 0)
                {
                    dgvUsers.Rows[0].Selected = true;
                    dgvUsers.CurrentCell = dgvUsers.Rows[0].Cells[0];
                }
                
                Console.WriteLine($"成功加载 {userList.Count} 个用户部门数据到表格");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"加载用户部门数据到表格失败: {ex.Message}");
                ShowAlert($"加载用户部门数据到表格失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 确认选择按钮
        /// </summary>
        private void btnConfirm_Click(object sender, EventArgs e)
        {
            try
            {
                if (dgvUsers.SelectedRows.Count > 0)
                {
                    var selectedRow = dgvUsers.CurrentRow.Index;
                   
                    if (selectedRow >= 0 && selectedRow < userList.Count)
                    {
                        SelectedUser = userList[selectedRow];
                        Console.WriteLine($"已选择用户: {SelectedUser.userName} (部门: {SelectedUser.departmentName})");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        ShowAlert("请选择有效的用户", "提示");
                    }
                }
                else
                {
                    ShowAlert("请先选择一个用户", "提示");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"选择用户失败: {ex.Message}");
                ShowAlert($"选择用户失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 显示提示信息
        /// </summary>
        private void ShowAlert(string message, string caption)
        {
            MessageBox.Show(message, caption, MessageBoxButtons.OK,
                caption == "成功" ? MessageBoxIcon.Information
                : caption == "提示" ? MessageBoxIcon.Information
                : MessageBoxIcon.Error);
        }

        /// <summary>
        /// 取消按钮
        /// </summary>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
